package com.newbe.security.service;

import com.newbe.security.entity.Permission;
import com.newbe.security.entity.User;
import com.newbe.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @Auther: Newbe
 * @Date: 2020/3/28 21:52
 * @Description:
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

       //1.根据用户名称查询数据库用户信息
        User user = userMapper.findByUsername(username);

        // 2.查询该用户信息权限
        if (user != null) {
            // 3.查询用户权限
            List<Permission> listPermission = userMapper.findPermissionByUsername(username);
            if (listPermission != null && listPermission.size() > 0) {
                List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                for (Permission permission : listPermission) {
                    // 4.获取用户权限
                    authorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
                    System.out.println("用户拥有权限："+permission.getPermName()+permission.getPermTag());
                }
                // 5.设置用户权限
                user.setAuthorities(authorities);
            }
        }
        //6.返回用户凭证信息
        return user;
    }
}
